package other;

import org.junit.jupiter.api.Test;

// 重排序
public class JmmTest {

    @Test
    public void testJMM() throws InterruptedException {
        CountEntity count = new CountEntity();
        new Thread(() -> {
            while (!count.isReady()) {
                Thread.yield();
            }
            System.out.println(count.getCount());
        }).start();

        count.setCount(1);
        count.setReady(true);//重排序可能会使这句比上句先执行，导致程序输出“0”
        Thread.sleep(100);
    }

    @Test
    public void testResort() throws InterruptedException {
        for (int i = 0; i < 100000; i++) {
            final int[] a = {0, 0};
            final int[] x = {0, 0};
            Thread one = new Thread(() -> {
                a[0] = 1;
                x[0] = a[1];
            });
            Thread two = new Thread(() -> {
                a[1] = 1;
                x[1] = a[0];
            });
            one.start();
            two.start();
            one.join();
            two.join();
            if (x[0] == 0 && x[1] == 0) {
                //此时发生重排序，one线程里面的两句代码执行顺序调换了！
                System.out.println(x[0] + "\t" + x[1]);
            }
        }
    }
}
